<?php
class App_Source_Media_Handler_Audio extends App_Source_Media_Handler
{
	private $_fileObj;	
	
	protected function InitFile()
	{
		$this->_fileObj = new ffmpeg_movie($this->_filePath);
		if (!$this->_fileObj || !$this->_fileObj->hasAudio() || !$this->_fileObj->getDuration())	
		{
			$this->SetError(Mozg_Lang::_('AUDIO_STREAM_NOT_FOUND'));
		}
		
		$this->_fileMimeType = 'audio/unknown';
		$this->_fileSize = filesize($this->_filePath);
		$this->_fileLength = $this->_fileObj->getDuration();			
	}
	
	public function CreateThumbNail()
	{
		if (false === $this->_fileThumbNail)
		{
			$this->_fileThumbNail = '';	
			
			$destPath = $this->GetDestPath();
			if (false === $destPath) return false;			
			
			$frameCount = (int)$this->_fileObj->getFrameCount();
			if ($frameCount)
			{
				$frame = $this->_fileObj->getFrame(ceil($frameCount / 2));
				if ($frame)
				{
					$image = $frame->toGDImage();
					if ($image)
					{	
						$filename = pathinfo($this->_filePath, PATHINFO_FILENAME);
						$thumbPath = $destPath.$filename. '-thumb.jpg';
						@ImageJpeg($image, $thumbPath, 90);
						@ImageDestroy($image);
						
						if (is_file($thumbPath))
						{
							$this->_fileThumbNail = $thumbPath;	
						}
					}
				}
			}
		}

		return $this->_fileThumbNail;		
	}	
	
	public function Convert($code)
	{
		$destPath = $this->GetDestPath();
		if (false === $destPath) 
		{
			$this->SetConvertStatus(App_Source_Media_Status::HasError);
			$this->SetError(Mozg_Lang::_('ERROR_OCCURED_WHILE_PROCCESSING_FILE'));
			return false;
		}		

		$fileInfo = pathinfo($this->GetFilePath());
		$destFile = $destPath.$fileInfo['filename']. '.mp3';	
		$command = 'ffmpeg -y -i %1$s -acodec libmp3lame -ab 128k -vn %2$s';	
		
		//$destFile = $destPath.$fileInfo['filename']. '.ogg';
		//$command = 'ffmpeg -y -i %1$s -ab 128k -vn %2$s';	
		
		$result = $this->RunShellCommand($command, $destFile, $code);		
		if (!$result) 
		{
			$this->SetConvertStatus(App_Source_Media_Status::HasError);
			$this->SetError(Mozg_Lang::_('ERROR_OCCURED_WHILE_PROCCESSING_FILE'));
			return false;
		}		
		
		$this->_fileMimeType = 'audio/mpeg';
		$this->SetConvertStatus(App_Source_Media_Status::NotProcessed);
		
		return $destFile;
	}
}